package com.itheima.reggie.controller;

import com.itheima.reggie.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.zip.DataFormatException;

/*
@date 2022年07月31日10:28
*/
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private  String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        //1.文件的名字是什么起名字
        //1,1获取原始文件图片名
        String originalFilename = file.getOriginalFilename();
        //1.2截取已点截取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        //1.3动态生成文件名不重复
        UUID uuid = UUID.randomUUID();
        //1.4拼接
        String fileName = uuid + suffix;
        //2.文件的存储路径在哪
         //2.1判断图片的目录是否存在,如果不存在则自动创建
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //3.将文件转存到指定目录
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return   R.success(fileName);
    }


    @GetMapping("/download")
    public void  downLoad(String name, HttpServletResponse response) throws IOException {
        FileInputStream fis=null;
        ServletOutputStream ous=null;
        try {
            //1.获取输入流 读取文件内容
            fis = new FileInputStream(new File(basePath + name));
            //2.获取输出流 写会到浏览器
             ous = response.getOutputStream();
            //3.设置响应头
            response.setContentType("image/jpg");
            //4.循环写
            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=fis.read(bytes))!=-1){
                ous.write(bytes,0,len);
                ous.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关流
            if(fis!=null){
                fis.close();
            }
            if(ous!=null){
                ous.close();
            }
        }


    }




}
